const moment = require('moment')
const user = require('./user')
const department = require('./department')
const auth = require('./auth')
const rest = require('./rest')

const code = "jinwin"

module.exports = app => {
    //获取公司token
    async function getToken(code) {
        const { model: { Company } } = app
        let row = await Company.findOne({
             where: {
                code
            },
        })
        var ts = (new Date().getTime() - new Date(row.created_at).getTime()) / 1000
        if (!row.token || ts > 7100) {
            //重新获取token
            const ret = await app.curl(`https://oapi.dingtalk.com/gettoken?corpid=${row.corpid}&corpsecret=${row.secret}`, {
                method: 'GET',
                dataType: 'json',
            });
            row.token = ret.data.access_token;
            row.save()
        }
        return row.token
    }

    //发起请求
    async function curl(url, param) {

        let access_token = await getToken(code)
        
        param = param || {}
        if(access_token){
            param.access_token = access_token
        }

        const ret = await app.curl(`https://oapi.dingtalk.com${url}`, {
            method: 'GET',
            dataType: 'json',
            data: param,
        });
        const res = ret.data;
        if (res.errcode) {
            throw new Error(`${url}请求失败！错误代码:${res.errcode} 错误信息: ${res.errmsg}`);
        }
        return res;
    }

    //新接口
    async function curl2(method, param) {
        let access_token = await getToken(code)

        let data = Object.assign({
            method, //API接口名称。
            session: access_token, //钉钉提供的授权Token，想了解详情，ISV开发者请点击这里，企业开发者请点击这里。若有疑问，咨询邮箱dingding_open_dingtalk#list.alibaba-inc.com。
            timestamp: moment().format('YYYY-MM-DD HH:mm:ss'), //	时间戳，
            format: 'json', //响应格式。默认为xml格式，可选值：xml，json。
            v: '2.0', //API协议版本，可选值：2.0。
            partner_id: '', //合作伙伴身份标识。
            simplify: true, //是否采用精简JSON返回格式，仅当format=json时有效，默认值为：false。
        }, param)

        const ret = await app.curl(`https://eco.taobao.com/router/rest`, {
            method: 'POST',
            dataType: 'json',
            data,
            "content-type": 'application/x-www-form-urlencoded',
        });
        const res = ret.data;
        if (res.error_response) {
            throw new Error(`${method}请求失败！错误代码:${res.error_response.code} 错误信息: ${res.error_response.msg} `);
        }
        if (!res.result.success) {
            throw new Error(`${method}请求失败！错误代码:${res.result.ding_open_errcode} 错误信息: ${res.result.error_msg}`);
        }
        return res;
    }

    return {
        user: new user({ curl }),
        department: new department({ curl }),
        auth: new auth({ curl }),
        rest: new rest({ curl: curl2 })
    }
}